package com.yunang.oa.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunang.oa.common.R;
import com.yunang.oa.entity.OaUser;
import com.yunang.oa.service.OaUserPlusService;
import com.yunang.oa.service.OaUserService;
import com.yunang.oa.service.impl.OaUserPlusServiceImpl;
import com.yunang.oa.vo.OaLogin;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/v1/oa/login")
public class OaLoginController {

    private final OaUserService oaUserService;

    private final OaUserPlusService oaUserPlusService;

    @Autowired
    public OaLoginController(OaUserService oaUserService, OaUserPlusService oaUserPlusService) {
        this.oaUserService = oaUserService;
        this.oaUserPlusService = oaUserPlusService;
    }


    @ApiOperation(value = "注册")
    @PostMapping("/register")
    public R RegisterOaUser(@RequestBody(required = true) OaLogin login){

        QueryWrapper<OaUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",login.getUserName());
        OaUser user = oaUserPlusService.getOne(wrapper);
        if(user==null){
            String md5Password = DigestUtils.md5DigestAsHex(login.getPassword().getBytes());
            login.setPassword(md5Password);

            OaUser oaUser = new OaUser();
            oaUser.setUserName(login.getUserName());
            oaUser.setPassword(login.getPassword());


            boolean b = oaUserPlusService.save(oaUser);

            return R.ok(b==true ?"注册成功" : "注册异常，请联系管理员处理");
        }else{
            return R.ok("用户名重复");
        }

    }

    @ApiOperation(value = "登陆")
    @PostMapping("/login")
    public R loginOaUser(@RequestBody(required = true) OaLogin login){

        QueryWrapper<OaUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",login.getUserName());
        OaUser user = oaUserPlusService.getOne(wrapper);

        //验证用户名是否正确
        if(user==null){
            return R.ok("查无此用户");
        }else{
            //验证密码是否正确
            String md5Password = DigestUtils.md5DigestAsHex(login.getPassword().getBytes());
            wrapper.eq("password",md5Password);
            user = oaUserPlusService.getOne(wrapper);

            if(user==null){
                return R.ok("密码错误");
            }else {
                return R.ok("登陆成功");
            }
        }

    }
}
